public class Solution10 {
    //188. 买卖股票的最佳时机 IV
    public int maxProfit(int k, int[] prices) {
        int n = prices.length;
        int[][] f = new int[n][k+1]; // f[i][j] 表示第i天，完成j次交易后处于买入状态的最大利润
        int[][] g = new int[n][k+1]; // g[i][j] 表示第i天完成j次交易后处于卖出状态的最大利润
        f[0][0] = -prices[0]; g[0][0] = 0;
        for (int i = 1; i <= k; i++) {
            f[0][i] = -0x3f3f3f3f;
            g[0][i] = -0x3f3f3f3f;
        }



        for (int i = 1; i < n; i++) {
            for (int j = 0; j < k+1; j++) {
                f[i][j] = Math.max(f[i-1][j],g[i-1][j]-prices[i]);
                g[i][j] = g[i-1][j];
                if (j-1 >= 0) {
                    g[i][j] = Math.max(g[i-1][j],f[i-1][j-1]+prices[i]);
                }
            }
        }
        int ret = g[n-1][0];
        for (int i = 0; i < k+1; i++) {
            if (ret < g[n-1][i]) {
                ret = g[n-1][i];
            }
        }
        return ret;
    }
}
